package lg.minecraft.plugin.library.common;

import lombok.Getter;
import org.bukkit.Bukkit;

/**
 * 服务器工具类
 * 提供服务端类型检测和类存在性检查等功能
 *
 * @author langle__
 * @version 1.0
 */
public class ServerUtil {

    private static ServerType serverType = null;
    private static ServerVersion serverVersion = null;

    /**
     * 获取当前服务端类型
     *
     * @return ServerType 服务端类型枚举
     */
    public static ServerType getServerType() {
        if (serverType == null) {
            serverType = detectServerType();
        }
        return serverType;
    }

    /**
     * 检测当前服务端类型
     *
     * @return ServerType 服务端类型
     */
    private static ServerType detectServerType() {
        // 检查是否为Folia
        if (hasClass("io.papermc.paper.threadedregions.RegionizedServer")) return ServerType.FOLIA;
        // 检查是否为Paper
        if (hasClass("com.destroystokyo.paper.PaperConfig")) return ServerType.PAPER;
        // 检查是否为Spigot
        if (hasClass("org.spigotmc.SpigotConfig")) return ServerType.SPIGOT;
        // 默认为Bukkit
        return ServerType.BUKKIT;
    }

    /**
     * 是否为Folia服务端
     *
     * @return boolean 如果是Folia返回true
     */
    public static boolean isFolia() {
        return getServerType() == ServerType.FOLIA;
    }

    /**
     * 是否为Paper服务端
     *
     * @return boolean 如果是Paper返回true
     */
    public static boolean isPaper() {
        ServerType type = getServerType();
        return type == ServerType.PAPER || type == ServerType.FOLIA;
    }

    public static ServerVersion getServerVersion() {
        if (serverVersion == null) {
            serverVersion = detectServerVersion();
        }
        return serverVersion;
    }


    private static ServerVersion detectServerVersion() {
        String name;

        name = Bukkit.getServer().getClass().getPackage().getName();
        String craftBukkit = name.substring(name.lastIndexOf('.') + 1);

        name = Bukkit.getBukkitVersion();
        String version = name.substring(0, name.indexOf('-'));

        return new ServerVersion(craftBukkit, version);
    }

    /**
     * 判断指定的类是否存在
     *
     * @param className 完整的类名
     * @return 如果类存在返回true，否则返回false
     */
    public static boolean hasClass(String className) {
        try {
            Class.forName(className);
            return true;
        } catch (Throwable e) {
            return false;
        }
    }

    /**
     * 服务端类型枚举
     */
    @Getter
    public enum ServerType {
        BUKKIT("bukkit"),
        SPIGOT("spigot"),
        PAPER("paper"),
        FOLIA("folia");

        private final String name;

        ServerType(String name) {
            this.name = name;
        }
    }

    @Getter
    public static class ServerVersion {
        private final String craftBukkit;
        private final String version;

        public ServerVersion(String craftBukkit, String version) {
            this.craftBukkit = craftBukkit;
            this.version = version;
        }
    }

}
